package com.xyyl.patient.common.easemob;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xyyl.patient.core.support.SpringContextHolder;
import com.xyyl.patient.core.util.DateUtils;
import com.xyyl.patient.entity.base.Token;
import com.xyyl.patient.service.base.EasemobService;

/**
 * @projectName:xyyl-patient-web
 * @ClassName: EasemobService
 * @Description:环信账号注册
 * @author chens
 * @date 2017年8月22日
 *
 */
public class EasemobApiService {

	private static Logger logger = LogManager.getLogger(EasemobApiService.class);

	private static EasemobService easemobService;

	private static EasemobService getEasemobService() {
		if (easemobService == null) {
			easemobService = SpringContextHolder.getBean("easemobService");
		}
		return easemobService;
	}

	public static String register(String userName, String passwd) {

		String registerCode = null;
		String token = getToken();
		logger.info("token:{}", token);
		// 封装用户对象
		JSONArray array = new JSONArray();
		JSONObject userJSON = new JSONObject();
		userJSON.put("username", userName);
		userJSON.put("password", passwd);
		array.add(userJSON);
		// 创建环信帐号
		List<Map<String, String>> users = EasemobRestClent.register(array.toString(), token);
		if (users.size() == 0) {
			logger.error("环信账号注册失败");
		} else {
			Map<String, String> dataMap = users.get(0);
			registerCode = dataMap.get("username");
		}
		return registerCode;
	}

	public static String getUserStatus(String userIm) {
		if (userIm == null) {
			return "";
		}
		String token = getToken();
		String result = EasemobRestClent.getStatus(userIm, token);
		return result;
	}

	private static String getToken() {

		Integer id = 1;
		Date date = new Date();

		Token token = getEasemobService().getToken(id);
		if (token != null) {
			// 计算token已存在的毫秒+预留更新时间
			long expiresTime = date.getTime() - DateUtils.toTimeMillis(token.getCreateDate()) + token.getReserve();
			// 判断是否超过token的有效期
			if (expiresTime >= token.getExpiresIn()) {
				Map<String, String> tokenMap = EasemobRestClent.getToken();
				token.setApplication(tokenMap.get("application"));
				token.setCreateDate(DateUtils.currentDatetime());
				token.setExpiresIn(Long.valueOf(tokenMap.get("expires_in")));
				token.setValue(tokenMap.get("access_token"));
				getEasemobService().updateToken(token);
			} else {
			}
		}
		return token.getValue();
	}

}
